package cz.muni.fi.rum.sender.senders;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

/**
 * Trida slouzi k posilani a prijimani RAP messages.
 * jednoduse posle do streamu string a pote ceka na response a tu vrati
 * @since v1.1
 * @version v1.0
 * @author pmikulasek
 */
public class MessageSenderImpl implements MessageSender {

    private final OutputStreamWriter outputNetworkStream;
    private final BufferedReader inputNetworkStream;

    public MessageSenderImpl(OutputStreamWriter outputNetworkStream, InputStreamReader inputNetworkStream) {
        this.outputNetworkStream = outputNetworkStream;
        this.inputNetworkStream = new BufferedReader(inputNetworkStream);
    }

    @Override
    public synchronized String send(String request) throws IOException {
        outputNetworkStream.write(request);
        outputNetworkStream.write("\n");
        outputNetworkStream.flush();
        return getResponse();
    }

    private String getResponse() throws IOException {
        StringBuilder builder = new StringBuilder();
        while (true) {
            if (inputNetworkStream.ready()) {
                String line;
                line = inputNetworkStream.readLine();
                if (!line.isEmpty()) {
                    builder.append(line);
                    builder.append("\n");
                } else {
                    builder.append(line);
                    if (inputNetworkStream.ready()) {
                        line = inputNetworkStream.readLine();
                        if (line.isEmpty()) {
                            //konec response
                            break;
                        } else {
                            builder.append(line);
                            builder.append("\n");
                        }
                    } else {
                        //konec response
                        break;
                    }
                }
            }
        }
        return builder.toString();
    }
}
